<?php
/**
 * Created by PhpStorm.
 * User: evenvi
 * Date: 16-3-14
 * Time: 下午2:11
 */

require "config.php";

$black_list_arr = explode(',', BLACKLIST);

if(DEBUG)
{
    file_put_contents('./data/test_content_time.txt', date('Y-m-d H:i:s', time())."\r\n", FILE_APPEND);
}

error_reporting(E_ALL);
date_default_timezone_set('PRC');

/*if(DISPLAY_HEADER)
{
    //打印http头信息,
    $header_content = "";
    foreach (getallheaders() as $name => $value) {
        $header_content .= "$name: $value\n";
    }
    file_put_contents('./data/test_header.txt', $header_content."\r\n\r\n", FILE_APPEND);
}*/


if(isset($_GET['action']))
{
    $_action =   $_GET['action'];
}
else
{
    echo "Parameter Error";
    die;
}


$post_data = file_get_contents("php://input");

//$post_data = iconv('GBK', 'UTF-8', $post_data);  //ssid base64编码之后不用再转码了

if(DEBUG)
{
    file_put_contents('./data/test_content.txt', $_action ."-----------" . $post_data."\r\n", FILE_APPEND);
}


if($_action == 'reportclient')
{
    _handle_client_data($post_data, $black_list_arr);
}
else if ($_action == 'reportap')
{
    _handle_ap_data($post_data, $black_list_arr);
}
else if($_action == 'regdev')
{
    _handle_reg_data($post_data);
}
else if($_action == 'reportibeacon')
{
    _handle_ibeacon_data($post_data);
}
else
{
    header('HTTP/1.0 404 Not Found(So Bad!)');
}

/*if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        foreach ($_SERVER as $name=>$value)
        {
            if(substr($name, 0, 5) == 'HTTP_')
            {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}*/

function _handle_client_data($post_data, $filter_mac)
{
    $attr_arr = array('devmac', 'climac', 'ssid', 'openwrt', 'bssid', 'time', 'signal');  //固定字段

    $all_str = '';
//    $post_line_arr = explode(chr(10), $post_data);
    $post_line_arr = preg_split('/[\n(\r\n)]+/', $post_data);
    foreach ($post_line_arr as $line_row)
    {
        if(!filter_mac($line_row, $filter_mac)) continue;

        $info_arr = array();
        $item_str = "";
        $post_arr = explode(',', $line_row);
        foreach($post_arr as $row)
        {
            $tmp_row = explode('":"', $row);
            $tmp_attr_name = trim(str_replace('"','', $tmp_row['0']));
            $tmp_attr_value = trim(str_replace('"','', $tmp_row['1']));

            if(in_array($tmp_attr_name, $attr_arr))
            {

                if($tmp_attr_name == 'ssid')
                {
                    $info_arr[$tmp_attr_name] = base64_decode($tmp_attr_value);
                }
                else if($tmp_attr_name == 'time')
                {
                    $info_arr[$tmp_attr_name] = date('Y-m-d H:i:s', $tmp_attr_value);
                }
                else
                {
                    $info_arr[$tmp_attr_name] = $tmp_attr_value;
                }
            }
            else
            {
                $item_str .= '[' . $tmp_attr_name .'='. $tmp_attr_value. "]\r\n";
            }
        }

        $info_str = "";
        foreach($info_arr as $key=>$row)
        {
            $info_str .= '['. $key.'='. $row .'] ';
        }

        $all_str .= (trim($item_str) == '[=]')?($info_str ."\r\n"):($info_str ."\r\n". $item_str);

    }

    if(MULTI_FILE)
    {
        $file_name = 'client_data_'. date('YmdHi', time()). '.txt';
    }
    else
    {
        $file_name = 'client_data.txt';
    }
    file_put_contents('./data/'.$file_name, $all_str, FILE_APPEND );

    }

function _handle_ap_data($post_data, $filter_mac)
{
    $all_ap_str = '';
//    $post_line_arr = explode(chr(10), $post_data);
    $post_line_arr = preg_split('/[\n(\r\n)]+/', $post_data);
    foreach ($post_line_arr as $line_row)
    {
        if(!filter_mac($line_row, $filter_mac)) continue;

        $info_str = "";
        $post_arr = explode(',', $line_row);
        foreach ($post_arr as $row)
        {
            $tmp_row = explode('":"', $row);
            $tmp_attr_name = trim(str_replace('"','', $tmp_row['0']));
            $tmp_attr_value = trim(str_replace('"','', $tmp_row['1']));
            if($tmp_attr_name == 'ssid')
            {
                $info_str .= '[' . $tmp_attr_name . '=' . base64_decode($tmp_attr_value) . '] ';
            }
            else if($tmp_attr_name == 'time')
            {
                $info_str .= '[' . $tmp_attr_name . '=' . date('Y-m-d H:i:s', $tmp_attr_value) . '] ';
            }
            else
            {
                $info_str .= '[' . $tmp_attr_name . '=' . $tmp_attr_value . '] ';
            }

        }
        $all_ap_str .= (trim($info_str) == '[=]')?("\r\n"):($info_str ."\r\n");
    }

    if(MULTI_FILE)
    {
        $file_name = 'ap_data_'. date('YmdHi', time()). '.txt';
    }
    else
    {
        $file_name = 'ap_data.txt';
    }
    file_put_contents('./data/'.$file_name, $all_ap_str, FILE_APPEND );
}

function _handle_reg_data($post_data)
{
    if(DISPLAY_REG)
    {
        file_put_contents('./data/test_reg.txt', "-----------" . $post_data."---------------------\r\n", FILE_APPEND);
    }
}


function _handle_ibeacon_data($post_data)
{
    file_put_contents("./data/ibeacon_data.txt", Date('Y-m-d H:i:s', time())."--".$post_data."\n\n", 8);
}

/**
 * 过滤设备mac
 * @param $line_str
 * @param $filter_arr
 * @return bool
 */
function filter_mac($line_str, $filter_arr)
{
    //        $tmp_devmac = preg_grep('/(?<="devmac":")(.*?)(?=")/', array($line_row)); //PHP JAVA等不支持向后匹配
    preg_match('/("devmac":")[0-9a-fA-F-:]{17}(?=")/i', $line_str, $matchs_result);
    $tmp_devmac = str_replace('"devmac":"', '', $matchs_result[0]);

    if(in_array($tmp_devmac, $filter_arr))
        return false;
    return true;
}

